package sas

import (
	"crypto/hmac"
	"crypto/sha1"
	"encoding/base64"
	"time"

	"github.com/micro-plat/lib4go/types"
)

//HmacSign hmac生成签名
func (n *sasClient) HmacSign(input types.XMap) (sign string, data types.XMap, err error) {
	input.SetValue(n.getTimespanName(), time.Now().Format("20060102150405"))
	input.SetValue(n.getEUIDName(), n.euid)
	return n.hmacSign(input)
}

func (n *sasClient) hmacSign(input types.XMap) (sign string, data types.XMap, err error) {
	//获取密钥
	res, err := n.SecretGet(HMACStr)
	if err != nil {
		return
	}

	return n.hmacSignKey(input, res.HmacSecret)
}

func (n *sasClient) hmacSignKey(input types.XMap, key string) (sign string, data types.XMap, err error) {
	raw := n.buildRaw(input, key, HMACStr)
	sign = hmacencrypt(raw, key)
	input.SetValue(n.getSignName(), sign)
	data = input
	return
}

//Encrypt HMAC加密
func hmacencrypt(data, key string) string {
	mac := hmac.New(sha1.New, []byte(key))
	mac.Write([]byte(data))
	expectedMAC := mac.Sum(nil)
	return base64.StdEncoding.EncodeToString(expectedMAC)
}
